<?php

class CartController extends Controller {

    public $layout = '//layouts/main_mini';
    public $pageKeyword = '';
    public $pageDesc    = '';



    public function init(){
    	
    	$criteria = new CDbCriteria;
    	$criteria->compare('zna_type',3);
    	
    	$criteria1 = clone $criteria;
    	$criteria1->compare('zna_url',"/".Yii::app()->getController()->id,true);
    	//如果一个控制器下存在多个菜单，则需细分
    	if(Nav::model()->count($criteria1)>1){
    		$criteria2 = clone $criteria;
    		$criteria2->compare('zna_url',"/".Yii::app()->getController()->id.'/'.$action->id,true);
    		$activeTop =  Nav::model()->find($criteria2);
    		if(empty($activeTop))
    			$activeTop =  Nav::model()->find($criteria1);
    	}else{
    		$activeTop =  Nav::model()->find($criteria1);
    	}
    	
    	if(!empty($activeTop)){
    		$this->pageTitle = $activeTop->zna_seotitle."-".F::setting('sitename');
    		$this->pageKeyword = $activeTop->zna_seokey;
    		$this->pageDesc = $activeTop->zna_seodesc;
    	}
    	return true;
    	
    
    }
    
    
    public function actionIndex() {        
        $cart = Yii::app()->cart;
        $mycart = $cart->contents();
        //print_r($mycart);exit;            
        $total = $cart->total();        
        $this->render('index', array(
            'mycart' => $mycart,
            'total' => $total
        ));
    }

    /*
     * 商品列表页单个商品加入购物车
     */

    public function actionAddCart() {        
        $qty = $_POST['qty']; //产品数量
        $id = $_POST['id']; //产品ID
        $spe = array();
        $spe = explode(':', $_POST['spe']);//产品规格
        $spes = implode(',',$spe); 
        $spemd5 = md5($id.$spes); //加密规格组

        $cart = Yii::app()->cart;       
        $mycart = $cart->contents();
        //取产品信息
        $model = Product::model()->findByPk($id); 
        //取产品优惠信息
        $promotion = CmpPromotion::model()->getPromotion($id);

        //取产品的积分信息
        //判断时否会员
        if(!empty(user()->userid)){
          $zmt_id = user()->memgroup['type']['zmt_id']; //取会员等级
          $propoint = ProPoint::model()->findByAttributes(array('zmt_id'=>$zmt_id,'zp_id'=>$model->zp_id));
          if($propoint){            
            $point     = $propoint->zpn_point; //所属等级积分
          }else{           
            $point     = $model->propoint[0]->zpn_point; //第一条积分
          }
        }else{        
          $point     = $model->propoint[0]->zpn_point; //第一条积分
        }
        
        if($promotion){ //有活动
           if($promotion['type']=='discount'){ //促销专区
            $price  = number_format($model->zp_price*$promotion['model']->zpd_discount/10,2,'.','');
            $active = '3';
           }elseif($promotion['type']=='promotion'){ //限时抢购
            $price  = $promotion['model']->zpt_price;
            $active = '2';
           }elseif($promotion['type']=='tuan'){ //团购
            $price  = $promotion['model']->zpt_price;
            $active = '1';
           }
        }else{
          //如果有规格
          if( !empty($_POST['spe']) ){
            $Attrs  = ProAttribute::model()->findByAttributes(array('zp_id'=>$id,'zps_md5'=>$spemd5));
            //库存错误
            if($qty > $Attrs->zpa_stock){
                print_r(1);
                exit;
            }
            //库存为0
            if($Attrs->zpa_stock==0){
                print_r(2);
                exit;
            }
            $speprice  = ProSpe::model()->findByAttributes(array('zp_id'=>$id,'zpa_id'=>$Attrs->zpa_id));
            $price = $speprice->zps_price;
          }else{
          $price = $model->zp_price;
          }
          $active = '0';
        }
        $insert_data = array(
          'id'          => $id,                       //产品ID
          'zm_id'       => $model->zm_id,             //会员ID
          'pic_url'     => $model->zp_pic,            //产品图片
          'sn'          => $model->zp_product_no,     //产品型号
          'title'       => $model->zp_name,           //产品名称
          'name'        => $model->zp_name,           //产品名称
          'exp_status'  => $model->zp_exp_status,     //物流类型
          'ze_id'       => $model->ze_id,             //运费模板
          'weight'      => $model->zp_weight,         //产品重量
          'saleprice'   => $model->zp_price,          //产品原价格
          'price'       => $price,                    //产品实价格
          'point'       => $point,                    //产品积分 
          'active'      => $active,                   //产品活动
          'qty'         => $qty,                      //产品数量
          'options'     => $spe                       //产品规格
        );       
        $data = $insert_data;             
        $cart->insert($data);
    }

    /*
     * 立即购买
     */

    public function actionAddToCart() {
        $session = new CHttpSession;
        $session->open();
        $cart = Yii::app()->cart;
        $mycart = $cart->contents();       
       
        $data = $_POST['proinfo'];
        //判断是否套餐
        if(!empty($data['packageid'])){
            $package = $data['product'];            
            //
            $packagecount = count($package);
           //节省的价格
           $xprice = $data['saleprice']-$data['price'];
           //平均价格
           $sprice =$xprice/$packagecount;
           $sprice = number_format($sprice,2,'.','');
           //第一个价格
           $onprice = $sprice*($packagecount-1);
           //(套餐标识ID)生成随机字符串
           $packagesid = create_randomstr();
            foreach ( $package as $key => $value ) {                 
                 //取第一条数据
                 $onedata =reset($package);
                 
                 //print_r($sprice);
                 //
                if($onedata['id']==$key){
                    $price = $xprice-$onprice;
                }else{
                    $price = $sprice;
                }
                $packageid = $data['packageid'];
                $exp_status = $data['exp_status'];//是否包邮               
                //取产品信息 
                 $model = Product::model()->findByPk($key);                                  
                 $insert_data = array(
                  'id'          => $model->zp_id,              //产品ID
                  'zm_id'       => $model->zm_id,             //会员ID
                  'pic_url'     => $model->zp_pic,            //产品图片
                  'sn'          => $model->zp_product_no,     //产品型号
                  'title'       => $model->zp_name,           //产品名称
                  'name'        => $model->zp_name,           //产品名称
                  'exp_status'  => $exp_status,               //物流类型
                  'ze_id'       => $value['zel_id'],             //运费模板
                  'weight'      => $model->zp_weight,         //产品重量
                  'saleprice'   => $model->zp_price,          //产品原价格                                           
                  'price'       => $model->zp_price-$price,    //产品实价格
                  'packagesid'   => $packagesid,                 //套装标识ID                   
                  'package'     => $value['packageid'],        //套装ID
                  'active'      => 5,                   //产品活动                 
                  'qty'         => $data['qty'],              //产品数量
                  'options'     => $value['spe']              //产品规格
                );       
                $data = $insert_data;
                //print_r($data);           
                $cart->insert($data);
            }                                           
            $this->redirect(array('/cart'));
            exit;
        }
        $data['name'] = $data['title'];
        $data['options'] = $data['spe'];
        
        $data['active'] = '0';
        //取产品信息
        $model = Product::model()->findByPk($data['id']);

        //取产品的积分信息
        //判断时否会员
        $points = !empty($model->propoint[0]->zpn_point)?$model->propoint[0]->zpn_point:0; //第一条积分
        if(!empty(user()->userid)){
          $zmt_id = user()->memgroup['type']['zmt_id']; //取会员等级
          $propoint = ProPoint::model()->findByAttributes(array('zmt_id'=>$zmt_id,'zp_id'=>$model->zp_id));
          if($propoint){            
            $data['point']     = $propoint->zpn_point; //所属等级积分
          }else{           
            $data['point']     = $points; //第一条积分
          }
        }else{        
          $data['point']     = $points; //第一条积分
        }

        $data['saleprice'] = $model->zp_price;
        //判断库存是否足够
        if(empty($data['qty'])){
          setflash(t('Qty Empty'));
          $this->redirect(array('/home/product/detail/','id'=>$model->zp_id));
          exit;
        }
        //库存不足
        if( $data['qty'] > $model->zp_inventory ){          
          setflash(t('Inventory Shortage'));
          $this->redirect(array('/home/product/detail/','id'=>$model->zp_id));          
          exit;
        }
        //取产品优惠信息
        $promotion = CmpPromotion::model()->getPromotion($data['id']);
        if($promotion){ //有活动
           if($promotion['type']=='discount'){ //促销专区
            $data['price'] = number_format($data['saleprice']*$promotion['model']->zpd_discount/10,2,'.','');
            $data['active'] = '3';
           }elseif($promotion['type']=='promotion'){ //限时抢购
            $data['price'] = $promotion['model']->zpt_price;
            $data['active'] = '2';
           }elseif($promotion['type']=='tuan'){ //团购
            $data['price'] = $promotion['model']->zpt_price;
            $data['active'] = '1';
           }
        }
        //print_r($data['price']);exit;
        if ($cart->insert($data)) {
            $this->redirect(array('/cart'));
        }
    }

    /*
     * 更新产品信息
     */
    public function actionUpdate() {
        $cart = Yii::app()->cart;
//        print_r($_POST);
//        exit;        
        $data = $_POST;
        foreach ($data as $k => $v) {
            Yii::app()->cart->update($v);
        }
        $this->redirect(array('/cart/index'));
    }

    /*
     * 删除单个产品
     */
    public function actionDelete() {
        $id = $_REQUEST['rowid'];

        $cart = Yii::app()->cart;
        $mycart = $cart->contents();
        $ids =array();
        //判断是否套餐
        if($mycart[$id]['packagesid']!=''){         
          foreach ($mycart as $key => $value) {
            if( $value['packagesid'] == $mycart[$id]['packagesid'] ){
                $ids[] = $key;
            }
          }
          //print_r($ids); 
          foreach ($ids as $k => $v) {
            $deldata = array(
                'rowid' => $v,
                'qty' => 0
            );
            Yii::app()->cart->update($deldata);
          }         
          print_r(json_encode($ids));
          exit;  
        }        
        $data = array(
            'rowid' => $id,
            'qty' => 0
        );
        if (Yii::app()->cart->update($data))            
            $return = 0;
            print_r(json_encode($return));
    }

    /*
     * 批量删除购物车产品
     */
    public function actionDeletes() {  
        $data = $_POST['rowid'];
        //print_r($data);exit;
        $cart = Yii::app()->cart;
        $mycart = $cart->contents();
        $ids =array();        
        foreach ($data as $k => $v) {
            //print_r($v);
            //判断是否套餐
            if($mycart[$v]['packagesid']!=''){    
              //取套餐所有的ID集     
              foreach ($mycart as $key => $value) {
                if( $value['packagesid'] == $mycart[$v]['packagesid'] ){
                    $ids[] = $key;
                }
              }
              //print_r($ids); 
              foreach ($ids as $k1 => $v1) {
                $deldatas = array(
                    'rowid' => $v1,
                    'qty' => 0
                );
                Yii::app()->cart->update($deldatas);
              }
            }
            $deldata = array(
                'rowid' => $v,
                'qty' => 0
            );
            Yii::app()->cart->update($deldata);
        }          
        $this->redirect(array('/cart/index'));
    }

    /*
     * 更新产品库存
     */
    public function actionQty() {  
        $data = $_POST;
        //print_r($data);exit; 
        $qtydata = array(
                'rowid' => $data['rowid'],
                'qty'   => $data['qty']
        );
        //取产品ID查询库存
        $cart = Yii::app()->cart->contents();        
        $productid = $cart[$data['rowid']]['id'];
        $model = Product::model()->findByPk($productid); 
        if($data['qty'] > $model->zp_inventory){
            echo 1;
        }else{
          Yii::app()->cart->update($qtydata);             
          $this->redirect(array('/cart/index'));
        }        
    }

    /*
     * 清空购物车
     */
    public function actionDestory() {
        $cart = Yii::app()->cart;
        $cart->destroy();
        $this->redirect(array('/cart/index'));
    }

    // Uncomment the following methods and override them if needed
    /*
      public function filters()
      {
      // return the filter configuration for this controller, e.g.:
      return array(
      'inlineFilterName',
      array(
      'class'=>'path.to.FilterClass',
      'propertyName'=>'propertyValue',
      ),
      );
      }
      public function actions()
      {
      // return external action classes, e.g.:
      return array(
      'action1'=>'path.to.ActionClass',
      'action2'=>array(
      'class'=>'path.to.AnotherActionClass',
      'propertyName'=>'propertyValue',
      ),
      );
      }
     */
}